package org.yecq.tradedata.save;

import com.jhhc.baseframework.data.record.SqlOperator;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.yecq.tradedata.algorithm.BollValue;

/**
 * 布林线值的存储
 *
 * @author yecq
 */
@Component
public class BollSaver {

    @Autowired
    private SqlOperator sql;

    // 保存或修改某一天的布林值，默认klind_id是存在的
    public void saveOrUpdateByKLineId(String kline_id, BollValue value) {
        // 看是否存在
        List<Map<String, Object>> list = this.sql.query("select * from futures_boll where futures_day_kline_id = ?", kline_id);
        if (list.isEmpty()) {
            // 添加
            this.sql.insert("insert into futures_boll (mid,top,bottom,futures_day_kline_id) value(?,?,?,?)", value.getMiddle(),
                    value.getTop(), value.getBottom(), kline_id);
        } else {
            // 修改
            String id = list.get(0).get("id") + "";
            this.sql.update("update futures_boll set mid=?,top=?,bottom=? where id = ?", value.getMiddle(),
                    value.getTop(), value.getBottom(), id);
        }
    }

    public void saveOrUpdateByCodeDate(String code, String date, BollValue value) {
        // 查找所在的k线
        String kline_id = getIdByCodeDate(code, date);
        if (kline_id != null) {
            saveOrUpdateByKLineId(kline_id, value);
        }
    }

    private String getIdByCodeDate(String code, String date) {
        List<Map<String, Object>> list = this.sql.query("select * from futures_day_kline where date=? and futures_id = "
                + "(select id from futures where code=?)", date, code.toUpperCase());
        if (list.isEmpty()) {
            return null;
        }

        return list.get(0).get("id") + "";
    }
}
